package com.dup.jxlh.admin.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dup.jxlh.admin.entities.model.Perm;
import com.dup.jxlh.admin.entities.model.Role;
import com.dup.jxlh.admin.entities.vo.PermVO;
import com.dup.jxlh.admin.entities.vo.RoleVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Many;

import java.math.BigInteger;
import java.util.ArrayList;

@Mapper
public interface RoleMapper extends BaseMapper<Role> {
    @Select("select * from role ${ew.customSqlSegment}")
    ArrayList<Role> getRoleList(Page page, @Param(Constants.WRAPPER) Wrapper<Role> wrapper);

    @Select("select * from perm where pid = 0")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "id", property = "children",
                    many = @Many(select = "getSonPerm"))
    })
    ArrayList<PermVO> getMainPerm();

    @Select("select * from perm where pid = #{pid}")
    ArrayList<Perm> getSonPerm(@Param("pid") BigInteger pid);

    @Select("select perm_id from perm_role where role_id = #{roleId}")
    BigInteger[] getRolePermIds(@Param("roleId") BigInteger roleId);

    @Select("select phone from admin where role_id = #{roleId} and is_enable = 1")
    String[] getRoleUsernames(@Param("roleId") BigInteger roleId);

    @Select("delete from perm_role where role_id = #{roleId}")
    Integer deleteRolePerm(@Param("roleId") BigInteger roleId);

    @Insert({"<script>",
            "insert into perm_role (perm_id,role_id)",
            "values",
            "<foreach item = 'value' index = 'key' collection = 'permIds' separator = ','>",
            "(#{value},#{id})",
            "</foreach>",
            "</script>"})
    Integer insertRolePerm(RoleVO roleVO);

}
